{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "%pylab qt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "from PyQt4 import QtCore, QtGui\n",
    "n_calc = [0]\n",
    "def calculate():\n",
    "    sin(rand(1000))\n",
    "    n_calc[0]+=1\n",
    "    timer.start()\n",
    "\n",
    "timer = QtCore.QTimer()\n",
    "timer.setInterval(0)\n",
    "timer.setSingleShot(True)\n",
    "timer.timeout.connect(calculate)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "from PyQt4 import QtCore, QtGui\n",
    "from psutil import cpu_percent\n",
    "from time import sleep\n",
    "from timeit import default_timer\n",
    "APP = QtGui.QApplication.instance()\n",
    "\n",
    "close('all')\n",
    "\n",
    "n_calc[0] = 0\n",
    "\n",
    "from time import time\n",
    "def sleep_loop(delay):\n",
    "   loop = QtCore.QEventLoop()\n",
    "   timer = QtCore.QTimer()\n",
    "   timer.setInterval(delay*1000)\n",
    "   timer.setSingleShot(True)\n",
    "   timer.timeout.connect(loop.quit)\n",
    "   timer.start()\n",
    "   loop.exec() # la loop prend en charge elle-même l'évenement du timer qui va la faire mourir après delay.\n",
    "\n",
    "def sleep_pe(delay):\n",
    "   tic = default_timer()\n",
    "   while(default_timer()<tic+delay):\n",
    "       APP.processEvents()\n",
    "\n",
    "def my_sleep(delay):\n",
    "    tic = default_timer()\n",
    "    if delay>1e-3:\n",
    "        sleep_loop(delay - 1e-3)\n",
    "    while(default_timer()<tic+delay):\n",
    "        APP.processEvents()\n",
    "        \n",
    "import asyncio\n",
    "\n",
    "async def sleep_coroutine(delay):\n",
    "    await asyncio.sleep(delay)\n",
    "    #loop.stop()\n",
    "\n",
    "loop = asyncio.get_event_loop()\n",
    "\n",
    "def sleep_asyncio(delay):\n",
    "    asyncio.ensure_future(sleep_coroutine(delay))\n",
    "    loop.run_forever()\n",
    "   \n",
    "MAX_TIME = 0.005\n",
    "\n",
    "\n",
    "\n",
    "for timer_on_off in (False, True):\n",
    "    for index, (func, label) in enumerate([ (sleep_asyncio, \"asyncio\"),\n",
    "                                            (sleep_loop, \"qeventloop\"),\n",
    "                                            (sleep_pe, \"processEvents\"),\n",
    "                                            (sleep, \"time.sleep\"),\n",
    "                                            (my_sleep, \"my_sleep\"), \n",
    "                                           ]):\n",
    "        if timer_on_off:\n",
    "            timer.start()\n",
    "        fig = figure()\n",
    "        times_measured = []\n",
    "        times_asked = []\n",
    "\n",
    "        n_calc_before = n_calc[0]\n",
    "        tic_for_func = default_timer()\n",
    "        cpu_percent() # call starts the cpu_percent averaging\n",
    "        for time_asked in linspace(0., MAX_TIME, 200):\n",
    "            #if int(time_asked*10000)%10==0:\n",
    "            #    print(time_asked)\n",
    "            for i in range(10):\n",
    "                tic = default_timer()\n",
    "                func(time_asked)\n",
    "                toc = default_timer()\n",
    "                times_measured.append(toc - tic)\n",
    "                times_asked.append(time_asked)\n",
    "        cpu_percents = cpu_percent()\n",
    "        toc_for_func = default_timer()\n",
    "        calc_done = (n_calc[0] - n_calc_before)/(toc_for_func - tic_for_func)\n",
    "        plot(times_asked, times_measured, '.')\n",
    "        plot([0, MAX_TIME], [0, MAX_TIME])\n",
    "        xlabel(\"time asked\")\n",
    "        ylabel(\"time measured\")\n",
    "        xlim(0, MAX_TIME)\n",
    "        ylim(0, MAX_TIME)\n",
    "        title(label + ' cpu_percent=' + str(cpu_percents) + ' calc/s=' + str(int(calc_done)))\n",
    "        if timer_on_off:\n",
    "            dirname = './images/with_timer/'\n",
    "        else:\n",
    "            dirname = './images/without_timer/'\n",
    "        fig.savefig(dirname + label + '.png')\n",
    "        timer.stop()\n",
    "        close('all')\n",
    "        for i in range(1000000):\n",
    "            APP.processEvents()\n",
    "timer.stop()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "%pylab qt\n",
    "import quamash\n",
    "from PyQt4 import QtCore, QtGui\n",
    "import asyncio\n",
    "\n",
    "from psutil import cpu_percent\n",
    "from time import sleep\n",
    "from timeit import default_timer\n",
    "APP = QtGui.QApplication.instance()\n",
    "\n",
    "\n",
    "n_calc = [0]\n",
    "def calculate():\n",
    "    sin(rand(1000))\n",
    "    n_calc[0]+=1\n",
    "    timer.start()\n",
    "\n",
    "timer = QtCore.QTimer()\n",
    "timer.setInterval(0)\n",
    "timer.setSingleShot(True)\n",
    "timer.timeout.connect(calculate)\n",
    "\n",
    "MAX_TIME = 0.005\n",
    "loop = quamash.QEventLoop()\n",
    "asyncio.set_event_loop(loop) \n",
    "\n",
    "async def sleep_coroutine(delay):\n",
    "    await asyncio.sleep(delay)\n",
    "    #tic = default_timer()\n",
    "    #if delay>0.001:\n",
    "        #await asyncio.sleep(delay - 0.001)\n",
    "    #while default_timer() < tic + delay:\n",
    "    #    APP.processEvents()\n",
    "\n",
    "timer.start()\n",
    "\n",
    "label = \"asyncio\"\n",
    "async def run():\n",
    "    fig = figure()\n",
    "    times_measured = []\n",
    "    times_asked = []\n",
    "\n",
    "    n_calc_before = n_calc[0]\n",
    "    tic_for_func = default_timer()\n",
    "    cpu_percent() # call starts the cpu_percent averaging\n",
    "    for time_asked in linspace(0., MAX_TIME, 200):\n",
    "        #if int(time_asked*10000)%10==0:\n",
    "        #    print(time_asked)\n",
    "        for i in range(10):\n",
    "            tic = default_timer()\n",
    "            await sleep_coroutine(time_asked)\n",
    "            toc = default_timer()\n",
    "            times_measured.append(toc - tic)\n",
    "            times_asked.append(time_asked)\n",
    "    cpu_percents = cpu_percent()\n",
    "    toc_for_func = default_timer()\n",
    "    calc_done = (n_calc[0] - n_calc_before)/(toc_for_func - tic_for_func)\n",
    "    plot(times_asked, times_measured, '.')\n",
    "    plot([0, MAX_TIME], [0, MAX_TIME])\n",
    "    xlabel(\"time asked\")\n",
    "    ylabel(\"time measured\")\n",
    "    xlim(0, MAX_TIME)\n",
    "    ylim(0, MAX_TIME)\n",
    "    title(label + ' cpu_percent=' + str(cpu_percents) + ' calc/s=' + str(int(calc_done)))\n",
    "    timer.stop()\n",
    "    fig.savefig('asyncio_no_correction.png')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "asyncio.ensure_future(run())\n",
    "#loop.run_forever() # this would be to launch the "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "%pylab qt\n",
    "import asyncio\n",
    "import scipy.fftpack\n",
    "import quamash\n",
    "from PyQt4 import QtCore, QtGui\n",
    "import asyncio\n",
    "loop = quamash.QEventLoop()\n",
    "asyncio.set_event_loop(loop) \n",
    "\n",
    "\n",
    "class Scope(object):\n",
    "    async def run_single(self, avg):\n",
    "        y_avg = zeros(100)\n",
    "        for i in range(avg):\n",
    "            await asyncio.sleep(1)\n",
    "            y_avg+=rand(100)\n",
    "        return y_avg\n",
    "\n",
    "class SpecAn(object):\n",
    "    scope = Scope()\n",
    "    \n",
    "    async def run_single(self, avg):\n",
    "        y = zeros(100, dtype=complex)\n",
    "        for i in range(avg):\n",
    "            trace = await self.scope.run_single(1)\n",
    "            y+= scipy.fftpack.fft(trace)\n",
    "        return y\n",
    "            \n",
    "sa = SpecAn()\n",
    "scope = Scope()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "v = asyncio.ensure_future(sa.run_single(10))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "v.result()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "async def my_loop():\n",
    "    for i in range(10):\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "%pylab qt\n",
    "import asyncio\n",
    "import scipy.fftpack\n",
    "import quamash\n",
    "from PyQt4 import QtCore, QtGui\n",
    "APP = QtGui.QApplication.instance()\n",
    "import asyncio\n",
    "from promise import Promise\n",
    "loop = quamash.QEventLoop()\n",
    "asyncio.set_event_loop(loop) \n",
    "\n",
    "\n",
    "class MyPromise(Promise):\n",
    "    def get(self):\n",
    "        while self.is_pending:\n",
    "            APP.processEvents()\n",
    "        return super(MyPromise, self).get()\n",
    "\n",
    "\n",
    "class Scope(object):\n",
    "    def __init__(self):\n",
    "        self.timer = QtCore.QTimer()\n",
    "        self.timer.setSingleShot(True)\n",
    "        self.timer.setInterval(1000)\n",
    "        self.timer.timeout.connect(self.check_for_curve)\n",
    "\n",
    "    def run_single(self, avg):\n",
    "        self.current_avg = 0\n",
    "        self.avg = avg\n",
    "        self.y_avg = zeros(100)\n",
    "        self.p = MyPromise()\n",
    "        self.timer.start()\n",
    "        return self.p\n",
    "\n",
    "    def check_for_curve(self):\n",
    "        if self.current_avg<self.avg:\n",
    "            self.y_avg += rand(100)\n",
    "            self.current_avg += 1\n",
    "            self.timer.start()\n",
    "        else:\n",
    "            self.p.fulfill(self.y_avg)\n",
    "\n",
    "\n",
    "class SpecAn(object):\n",
    "    scope = Scope()\n",
    "\n",
    "    def __init__(self):\n",
    "        timer = QtCore.QTimer()\n",
    "        timer.setSingleShot(True)\n",
    "        timer.setInterval(1000)\n",
    "\n",
    "    def run_single(self, avg):\n",
    "        self.avg = avg\n",
    "        self.current_avg = 0\n",
    "        self.y_avg = zeros(100, dtype=complex)\n",
    "        p = self.scope.run_single(1)\n",
    "        p.then(self.average_one_curve)\n",
    "        self.p = MyPromise()\n",
    "        return self.p\n",
    "\n",
    "    def average_one_curve(self, trace):\n",
    "        print('av')\n",
    "        self.current_avg+=1\n",
    "        self.y_avg+=scipy.fftpack.fft(trace)\n",
    "        if self.current_avg>=self.avg:\n",
    "            self.p.fulfill(self.y_avg)\n",
    "        else:\n",
    "            p = self.scope.run_single(1)\n",
    "            p.then(self.average_one_curve)\n",
    "\n",
    "sa = SpecAn()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "p = sa.run_single(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "p.is_fulfilled"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "p.get()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "sa.avg"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "s"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "%pylab qt\n",
    "import asyncio\n",
    "import scipy.fftpack\n",
    "import quamash\n",
    "from PyQt4 import QtCore, QtGui\n",
    "import asyncio\n",
    "loop = quamash.QEventLoop()\n",
    "asyncio.set_event_loop(loop) \n",
    "\n",
    "\n",
    "class Scope(object):\n",
    "    async def run_single(self, avg):\n",
    "        y_avg = zeros(100)\n",
    "        for i in range(avg):\n",
    "            await asyncio.sleep(1)\n",
    "            y_avg+=rand(100)\n",
    "        return y_avg\n",
    "\n",
    "\n",
    "class Na(object):\n",
    "    async def run_single(self, avg):\n",
    "        y_avg = zeros(100)\n",
    "        for i in range(avg):\n",
    "            await asyncio.sleep(1)\n",
    "            y_avg+=rand(100)\n",
    "        return y_avg\n",
    "\n",
    "scope = Scope()\n",
    "na = Na()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "async def my_coroutine(n):\n",
    "    c1 = zeros(100)\n",
    "    c2 = zeros(100)\n",
    "\n",
    "    for i in range(n):\n",
    "        print(\"launching f\")\n",
    "        f = asyncio.ensure_future(scope.run_single(1))\n",
    "        print(\"launching g\")\n",
    "        g = asyncio.ensure_future(na.run_single(1))\n",
    "        print(\"=======\")\n",
    "        c1+= await f\n",
    "        c2+= await g\n",
    "        print(\"f returned\")\n",
    "        print(\"g returned\")\n",
    "\n",
    "    return c1 + c2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "p = asyncio.ensure_future(my_coroutine(3))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "p.result()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "p.result?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "my_coroutine"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "asyncio.ensure_future(my_coroutine(1))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "obj = my_coroutine(1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "obj.__await__"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "class MyAwaitable(object):\n",
    "    def __await__(self):\n",
    "        return ((x for x in range(5)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "m = MyAwaitable()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "p = asyncio.ensure_future(m)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "p.result()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "m = MyFuture()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "p = asyncio.ensure_future(m)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "p.done()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "m.set_result(5)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "p"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "p.result()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "from asyncio.futures import Future\n",
    "\n",
    "class MyFuture(Future):\n",
    "    def __await__(self):\n",
    "        self.timer = QtCore.QTimer()\n",
    "        self.timer.timeout.connect(lambda : self.set_result(rand(100)))\n",
    "        self.timer.setSingleShot(True)\n",
    "        self.timer.setInterval(1000)\n",
    "        self.timer.start()\n",
    "        print('awaiting')\n",
    "        \n",
    "class AsyncScope(object):\n",
    "    def run_single(self, avg):\n",
    "        self.f = MyFuture()\n",
    "        return self.f\n",
    "    \n",
    "a = AsyncScope()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "f"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "f = a.run_single(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "a.f.set_result(6)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "f"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "p = asyncio.ensure_future(a.run_single(3))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "p.done()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "p.__await__()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "p.result()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
